<script setup lang="js">
import {computed, onBeforeMount, ref} from "vue";
import {ElMessage} from "element-plus";
import {devApiList} from "@main-window/stores/dev/storeDevtools.js";
import SummonerName from "@share/components/lcu/LcuSummonerName.vue";

onBeforeMount(()=>{
  initFunc();
  certificate.value=window.api_developer.getCertificate();
})

const certificate= ref();
const apiRequestData = ref({});

//url参数数据
const pathData=ref({});

const apiResponseData =ref({
  "data":""
});

const options = {
  "json":1,
  "blob":2,
}
const methods=["GET","POST"]


const doSendRequest = ()=>{
  resultIsLoading.value = true;
  apiResponseData.value.data = "";
  showMode.value=options[apiRequestData.value.responseType]

  const param = buildPram();
  const useFullPathData= useFullPathObjFunc();
  console.log(useFullPathData)
  const invokeParam = {...param,"url":replaceUrlPathDataFunc(param.url,useFullPathData)};
  console.log(`开始调用dev接口，入参如下`,invokeParam);
  window.api_developer.api_invoke(invokeParam).then(res=>{
    resultIsLoading.value = false;

    if(showMode.value===1){
      apiResponseData.value.data=res.data;
    }else{
      converterToBase64Img(res.data);
    }
    ElMessage.success({
      message: "接口响应成功",
      duration:500
    });


    devApiList().addApi({"key":param.url,"param":param,"pathDataCache":useFullPathData})

  }).catch(err=>{
    resultIsLoading.value = false;
    console.error("接口请求失败",err);
    ElMessage.error({
      message: `接口请求失败,message:${err.message}`,
      duration:2000
    })
  })
}

const replaceUrlPathDataFunc=(url,data)=>{
  return  url.replace(/\${(.*?)}/g, (match, key) => data[key]);
}

const converterToBase64Img=(data)=>{
  function blobToBase64(blob) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result); // 成功时返回 Base64 字符串
      reader.onerror = reject; // 失败时抛出错误
      reader.readAsDataURL(blob); // 开始读取 Blob
    });
  }
  blobToBase64(data)
      .then(base64String => {
        apiResponseData.value.data=base64String;
      })
      .catch(error => {
        console.error('转换失败:', error);
      });
}

const buildPram=()=>{
  let url = apiRequestData.value.url;
  url=url??''.trim();
  url = url.startsWith("/")?url.substring(1):url;
  const obj = {
    "url":url,
    "method":apiRequestData.value.method,
    "body": apiRequestData.value.body,
    "responseType":apiRequestData.value.responseType
  }
  return obj;
}

const useFullPathObjFunc=()=>{
  const filed = dynamicFields.value;
  const obj = {};
  for(let  item  of Object.keys(pathData.value)){
    if(filed.includes(item)){
      obj[filed]=pathData.value[filed];
    }
  }
  console.log(obj);
  return obj;
}

const quoteRequest=({key,param,pathDataCache})=>{
  apiRequestData.value = {...param};
  pathData.value={...pathDataCache};
  ElMessage.success({
    message:`引用接口${param.url}成功`,
    duration:500
  })
}

const resultIsLoading = ref(false)
const showMode = ref(1)

const initFunc=()=>{
  apiRequestData.value.method=methods[0];
  apiRequestData.value.responseType=Object.keys(options)[0];
  apiRequestData.value.url="";
  apiRequestData.value.body="";
  apiResponseData.value.data = "";
  pathData.value = {};
}



const dynamicFields=computed(()=>{
  const reg = /\$\{(.+?)\}/;
  const reg_g = /\$\{(.+?)\}/g;
  const result = apiRequestData.value?.url?.match(reg_g)??[];

  const  list = []
  for (let i = 0; i < result.length; i++) {
    const item = result[i]
    list.push(item.match(reg)[1])
  }
  return list;
})
</script>

<template>

  <div style="width: 100%;display: flex">

    <div style="flex-grow: 1">
      <el-form>
        <el-form-item label="URL">
          <div style="display: flex;width: 100%">
            <el-select style="width: 100px"   v-model="apiRequestData.method">
              <el-option v-for="item in methods"
                         :key="item"
                         :value="item"
                         :label="item"
              >
              </el-option>
            </el-select>
            <el-input v-model="apiRequestData.url">
              <template #prepend>
                https://127.0.0.1:{{certificate.port}}
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%;display: flex;flex-wrap: wrap;align-items: center" label="Path参数">
          <div v-for="item in dynamicFields" style="margin:0 12px">
            <el-text>{{item}}:</el-text>  <el-input v-model="pathData[item]" style="width: 160px"></el-input>
          </div>

        </el-form-item>
        <el-form-item label="Body">
          <el-input type="textarea" v-model="apiRequestData.body" :rows="10">
          </el-input>
        </el-form-item>

        <el-form-item label="响应类型">
          <el-select style="width: 200px" v-model="apiRequestData.responseType">
            <el-option v-for="item in Object.keys(options)"
                       :key="item"
                       :value="item"
                       :label="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button-group>
            <el-button type="primary" @click="doSendRequest">发送</el-button>
            <el-button @click="initFunc">重置</el-button>
          </el-button-group>
        </el-form-item>

      </el-form>

      <el-divider></el-divider>

      <div v-loading="resultIsLoading">
        <json-viewer
            style="max-height: 100vh;overflow: scroll"
            v-if="showMode===1"
            :value="apiResponseData.data"
            :expand-depth="5"
            sort
            copyable
        >
          <template #copy>
            拷贝数据
          </template>
        </json-viewer>
        <el-text v-else-if="showMode===2">
          <el-image
              :src="apiResponseData.data"
          ></el-image>
        </el-text>
      </div>

    </div>

    <el-divider direction="vertical" style="height: 90vh;margin: 0 12px 0 24px"></el-divider>

    <div style="width: 500px;display: flex;flex-direction: column" >
      <el-card style="margin-bottom: 24px" >
        Token：  <SummonerName :name="certificate.token" :show-num="false"/>
        <br>
        Port:   <SummonerName :name="certificate.port" :show-num="false"/>
      </el-card>
      <div v-for="item of devApiList().apis" style="display: flex;width: 100%;justify-content: space-between;align-items: center">
        <el-tag style="width: 60px">{{item?.param?.method}}</el-tag>
        <el-button text @click="quoteRequest(item)">
          <el-text truncated type="info" style="width: 300px">{{item.key}}</el-text>
        </el-button>
        <el-button @click="devApiList().deleteApi(item.key)">删除</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>